package com.example.livebroadcast.dao;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;


public abstract class IRedisDAO<T> {
	
	@Autowired
	protected RedisTemplate<String, Object> redisTemplate;

	@Resource
	protected HashOperations<String, String, T> hashOperations;

	protected abstract String getRedisKey();

	/***
	 * 添加
	 * 
	 * @paramkey key
	 * @paramdoamin 对象
	 * @paramexpire 过期时间(单位:秒),传入-1 时表示不设置过期时间
	 */
	public void put(String key, T domain, long expire) {
		hashOperations.put(getRedisKey(), key, domain);
		if (expire != -1) {
			redisTemplate.expire(getRedisKey(), expire, TimeUnit.SECONDS);
		}
	}

	public void remove(String key) {
		hashOperations.delete(getRedisKey(), key);
	}

	public T get(String key) {
		return hashOperations.get(getRedisKey(), key);
	}

	public List<T> getAll() {
		return hashOperations.values(getRedisKey());
	}

	public Set<String> getKeys() {
		return hashOperations.keys(getRedisKey());
	}

	public boolean isKeyExists(String key) {
		return hashOperations.hasKey(getRedisKey(), key);
	}
	
	public long count() {
		return hashOperations.size(getRedisKey());
	}
	
	public void empty() {
		Set<String> set = hashOperations.keys(getRedisKey());
		set.stream().forEach(key -> hashOperations.delete(getRedisKey(), key));
	}
}
